package pl.alipiec.stockview.master;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Collection;
import java.util.LinkedList;

import javax.jms.MessageProducer;
import javax.jms.TextMessage;

import org.hornetq.core.logging.Logger;

import pl.alipiec.stockview.Configuration;
import pl.alipiec.stockview.StockViewException;

/**
 * Klasa glownego brokera pobierającego informacje o cenie akcji
 * 
 * @author Aleksandra Lipiec
 * 
 */
public class MasterBroker extends Broker {

	private MessageProducer mainProducer;

	private IndexData indexData;
	
	private Logger log = Logger.getLogger(getClass());
	private int frequency;

	public MasterBroker() {
		Configuration conf = new Configuration();
		conf.loadConfiguration();
		indexData = conf.getIndexes();
		frequency = conf.getFrequency();
		log.info("configuration loaded");
	}

	public void create() throws StockViewException {
		mainProducer = getTopicProducer("/topic/mainBroker");

	}

	/**
	 * Wysylanie wiadomosci
	 * 
	 * @param stock
	 * @throws StockViewException
	 */
	public void sendMessage(Stock stock) throws StockViewException {
		try {
			TextMessage message = createMessage(stock);
			System.out.println("Sent message: " + message.getText());
			for (String index : stock.getIndexes()) {
				message.setStringProperty("indexName", index);
				mainProducer.send(message);
			}
		} catch (Exception e) {
			System.out.println("Error while sending message");
			e.printStackTrace();
			throw new StockViewException(e);
		}
	}

	/**
	 * Pobiera notowania przez URL
	 * 
	 * @return
	 * @throws IOException
	 */
	public Collection<Stock> downloadStocksOnet() {
		Collection<Stock> stocks = new LinkedList<Stock>();


		for (String index : indexData.keySet()) {
			BufferedReader reader = null;
			try {
				URL stockUrl = new URL(indexData.get(index));
				reader = new BufferedReader(new InputStreamReader(stockUrl
						.openStream()));
				reader.readLine();
				reader.readLine();
				reader.readLine();

				String line;
				while ((line = reader.readLine()) != null) {
					stocks.add(new Stock(line, index));
				}
			} catch (IOException e) {
				log.error(e);
				e.printStackTrace();
			} finally {
				try {
					reader.close();
				} catch (Exception e) {
					log.error(e);
				}
			}

		}

		return stocks;
	}
	
	public int getFrequency(){
		return frequency;
	}
	
	public static void main(String[] args) {
		MasterBroker broker = new MasterBroker();

		try {

			broker.connect();
			broker.create();
			while (true) {
				for (Stock stock : broker.downloadStocksOnet()) {
					broker.sendMessage(stock);
				}
				Thread.sleep(broker.getFrequency()*1000);
			}

		} catch (InterruptedException e) {
			
		} catch (StockViewException e) {
			broker.logError(e);
			e.printStackTrace();
		} finally {
			broker.closeConnection();
		}
	}
}
